﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzyGoEzySystem.Models;
using EzyGoEzySystem.Services;
using System.Web.Security;

namespace EzyGoEzySystem.Controllers
{
    public class RegisterController : Controller
    {
        //
        // GET: /Register/

        public ActionResult Index()
        {
            RegisterModel registerModel = new RegisterModel();
            registerModel.PaymentMethods = new SelectList(DataAccess.GetPaymentMethods());
            return View(registerModel);
        }

        //
        // POST: /Register

        [HttpPost]
        public ActionResult Index(RegisterModel account)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // check if the account already exists
                    if (!DataAccess.IsUsernameExisted(account.Username))
                    {
                        DataAccess.AddNewAccount(account);
                        FormsAuthentication.SetAuthCookie(account.Username, false);
                        Session["Account"] = DataAccess.GetAccount(account.Username);
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "Username already taken");
                    }
                }
            }
            catch
            {
                return View(account);
            }

            return View(account);
        }
    }
}
